package com.lanhai.system;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.lanhai.Main;
import com.lanhai.enums.Step;
import com.lanhai.javaBean.StationBean;
import com.lanhai.model.Agv;
import com.lanhai.model.CacheShelf;
import com.lanhai.model.ControlArea;
import com.lanhai.model.FreeArea;
import com.lanhai.model.Guidepost;
import com.lanhai.model.Job;
import com.lanhai.model.Park;
import com.lanhai.model.Station;
import com.lanhai.utils.CommandUtil;
import com.lanhai.utils.HexUtil;
import com.lanhai.utils.StringUtil;
import com.lanhai.utils.UDPUtil;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;


/**
 * 查询系统数据
 * 用GET请求
 * @author liangmin
 *
 */
public class QueryHandler implements HttpHandler {
	
	public Main main;
	
	private static final Logger logger = Logger.getLogger(QueryHandler.class);
	
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        InputStream is = httpExchange.getRequestBody();
        
        //String requestData = is2string(is);
        //System.out.println(requestData); 
        String queryParams = httpExchange.getRequestURI().getQuery();
        logger.info("控制台地址：" + httpExchange.getRemoteAddress().getAddress().getHostAddress());
        main.controlIp = httpExchange.getRemoteAddress().getAddress().getHostAddress();
        //System.out.println(queryParams);
        String response = "{没有对应数据}";
        if(queryParams.equals("agv")){//AGV列表
    		Map<Integer,Agv> map = main.agvMap;	
    		response = JSON.toJSONString(map);        	
        }else if(queryParams.equals("ca")){//交管区列表
    		//Map<Integer,ControlArea> map = main.controlAreaMap;	
    		Map<Integer,ControlArea> newMap = new HashMap<Integer,ControlArea>();
    		for(Map.Entry<Integer, ControlArea> m:main.controlAreaMap.entrySet()){
    			ControlArea ca = m.getValue();
    			ControlArea nca = new ControlArea();
    			nca.setId(ca.getId());
    			nca.setName(ca.getName());
    			//nca.setMapXArr(ca.getMapXArr());
    			//nca.setMapYArr(ca.getMapYArr());
    			nca.setRunAgvId(ca.getRunAgvId());
    			nca.setBaseX(ca.getBaseX());
    			nca.setBaseY(ca.getBaseY());
    			nca.setFlag(ca.getFlag());
    			newMap.put(nca.getId(), nca);
    		}
    		response = JSON.toJSONString(newMap);           	
        }else if(queryParams.equals("fa")){//自由区列表
        	Map<Integer,FreeArea> newMap = new HashMap<Integer,FreeArea>();
        	for(Map.Entry<Integer, FreeArea> m:main.freeAreaMap.entrySet()){
        		FreeArea fa = m.getValue();
        		FreeArea nfa = new FreeArea();
        		nfa.setId(fa.getId());
        		nfa.setName(fa.getName());
        		nfa.setMapXArr(fa.getMapXArr());
        		nfa.setMapYArr(fa.getMapYArr());
        		newMap.put(nfa.getId(), nfa);
        	}
        	response = JSON.toJSONString(newMap); 
        }else if(queryParams.equals("job")){//任务列表
        	List<Job> jobList = main.jobList;
        	Map<String, Object> map = new HashMap<String, Object>();
        	map.put("success", true);
        	map.put("data", jobList);
        	response = JSON.toJSONString(map); 
        	//System.out.println("response: " + response); 
        }else if(queryParams.equals("gp")){//地标列表
        	Map<Integer,Guidepost> map = main.guidepostMap;
        	response = JSON.toJSONString(map); 
        }else if(queryParams.equals("park")){//工位列表
        	Map<Integer,Park> map = main.parkMap;
        	response = JSON.toJSONString(map); 
        }else if(queryParams.equals("tw")){//交管等待AGV列表
        	response = JSON.toJSONString(main.waitAgvList);
        }else if(queryParams.equals("station")){//机台列表
        	response = JSON.toJSONString(main.stationMap);
        }else if(queryParams.equals("path")){//线路列表
        	response = JSON.toJSONString(main.mapPathMap);
        }else if(queryParams.equals("params")){//系统参数
        	response = JSON.toJSONString(main.paramList);
        }else if(queryParams.equals("step")){//工序列表
        	List<Map<String, Object>> stepList = Step.getList();
        	response = JSON.toJSONString(stepList);
        }else if(queryParams.equals("agvList")){//AGV列表
        	List<Agv> agvList = new ArrayList<Agv>();
        	for(Map.Entry<Integer, Agv> m:main.agvMap.entrySet()){
        		agvList.add(m.getValue());
        	}
        	response = JSON.toJSONString(agvList);
        }else if(queryParams.equals("stationList")){//机台列表
        	List<Station> stationList = new ArrayList<Station>();
        	for(Map.Entry<String, Station> m:main.stationMap.entrySet()){
        		stationList.add(m.getValue());
        	}
        	StationBean.IdSort(stationList);
        	response = JSON.toJSONString(stationList);
        }else if(queryParams.equals("parkList")){//泊位列表
        	List<Park> parkList = new ArrayList<Park>();
        	for(Map.Entry<Integer, Park> m:main.parkMap.entrySet()){
        		parkList.add(m.getValue());
        	}
        	response = JSON.toJSONString(parkList);
        }else if(queryParams.equals("caList")){//交管区列表
        	List<ControlArea> caList = new ArrayList<ControlArea>();
        	for(Map.Entry<Integer, ControlArea> m:main.controlAreaMap.entrySet()){
    			ControlArea ca = m.getValue();
    			ControlArea nca = new ControlArea();
    			nca.setId(ca.getId());
    			nca.setName(ca.getName());
    			//nca.setMapXArr(ca.getMapXArr());
    			//nca.setMapYArr(ca.getMapYArr());
    			nca.setRunAgvId(ca.getRunAgvId());
    			nca.setFlag(ca.getFlag());
    			caList.add(nca);
        	}
        	response = JSON.toJSONString(caList);
        }else if(queryParams.equals("reset")){
        	main.resetData();
        }else if(queryParams.contains("reload")){
        	Map<String, String> map = StringUtil.Split(queryParams);
        	main.mainAction.reloadData(map);
        }else if(queryParams.contains("fins")){
        	response = testFins();
        }else if(queryParams.equals("cache")) {
        	List<CacheShelf> list = new ArrayList<CacheShelf>();
        	for (Map.Entry<String, CacheShelf> m : main.cacheShelfMap.entrySet()) {
				list.add(m.getValue());
			}
        	response = JSON.toJSONString(list);
        }else if(queryParams.equals("carun")) {
        	Map<Integer,ControlArea> newMap = new HashMap<Integer,ControlArea>();
    		for(Map.Entry<Integer, ControlArea> m:main.controlAreaMap.entrySet()){
    			ControlArea ca = m.getValue();
    			ControlArea nca = new ControlArea();
    			nca.setId(ca.getId());
    			nca.setName(ca.getName());
    			//nca.setMapXArr(ca.getMapXArr());
    			//nca.setMapYArr(ca.getMapYArr());
    			nca.setRunAgvId(ca.getRunAgvId());
    			nca.setRunAgvList(ca.getRunAgvList());
    			nca.setBaseX(ca.getBaseX());
    			nca.setType(ca.getType());
    			nca.setBaseY(ca.getBaseY());
    			nca.setFlag(ca.getFlag());
    			newMap.put(nca.getId(), nca);
    		}
    		response = JSON.toJSONString(newMap);  
        }
        
        is.close();
        
        Headers responseHeaders = httpExchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/json;charset=utf-8");
        responseHeaders.set("Access-Control-Allow-Origin", "*");
        responseHeaders.set("Cache-Control","no-cache");
        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes().length); 
        OutputStream os = httpExchange.getResponseBody();
        //System.out.println(response);
        logger.info("Http请求：" + queryParams + "数据");
        os.write(response.getBytes());
        os.flush();
        os.close();  
    }
	
    public void init(Main main){
    	this.main = main;
    }
    
//    private String is2string(InputStream is) throws IOException {
//        final int bufferSize = 1024;
//        final char[] buffer = new char[bufferSize];
//        final StringBuilder out = new StringBuilder();
//        Reader in = new InputStreamReader(is, "UTF-8");
//        
//        for (; ; ) {
//            int rsz = in.read(buffer, 0, buffer.length);
//            if (rsz < 0)
//                break;
//            out.append(buffer, 0, rsz);
//        }
//        return out.toString();
//    }
    
    public String testFins(){
    	String plcIp = "10.221.100.118";
    	String pcIp = "10.221.69.40";
    	int action = 1;
    	int target = 4600;
		byte[] sendByte = CommandUtil.getFinsHead(plcIp, pcIp, action, target);
		System.out.println(HexUtil.byte2HexStr(sendByte));
		int port = 9605;
		byte[] buf = UDPUtil.sendData4Fins(sendByte, plcIp, port, action, main.mainAction, 2);
		return HexUtil.byte2HexStr(buf);
    }
    
}
